//yw 1初始化
layui.use(['form','layer','flow','table','element'],function(){
    var $ = layui.jquery;
    var form = layui.form;
    var table= layui.table;
    var layer = layui.layer;
    var flow = layui.flow;
    var element = layui.element;
    var schoolData = null;//yw 学校数据用于填充学校下拉框，防止反复从服务器下载学校数据
    var tBuildData = null;
    var classroomData = null;
    var tBuildID_v = null;//xqr 记录选中的教学楼Id
    //yw 2显示列表
    var tableIns = table.render({
        elem: '#list',
        url : '/device/queryDevice',
        cellMinWidth : 95,
        page : true,
        width : 1000,
        height : 670,
        limit : 15,
        limits : [15,10,20,30],
        id : "listTable",
        method:'post',
        cols : [[
            // {field: 'eqid', title: 'ID', width:180,align:'center'},  //xqr
            // {field: 'eqname', title: '设备名', width:100,align:'center'},
            {field: 'tbuildname', title: '教学楼', width:120,align:'center'},
            {field: 'classroom', title: '教室', width:140,align:'center'},
            {field: 'afgateway', title: '所属网关', width:160,align:'center'},
            {field: 'addtime', title: '添加时间',width:180,align:'center'},
            {field: 'onlstatus', title: '在线状态',width:100,align:'center',templet:function(d){return d.onlstatus=='1'?'在线':'离线'}},
            {fixed:"right",title: '数据统计', width:100,toolbar:'#listRowBar2',align:"center"},
            {fixed:"right",title: '操作', toolbar:'#listRowBar',align:"center"}
        ]],
        where:{buildId:tBuildID_v}//xqr 添加参数
    });
    //yw 3操作 1)模糊查询
    $(".search_btn").on("click",function(){
        var searchVal = $(".searchVal").val().trim();
        var onlineStatus = $("#onlineStatus").val();
        var url_Address = "/device/queryDevice";
        /*var url_Address = "/device/queryDevice?";
        if(searchVal!=""){
            url_Address = url_Address+"&afGateway="+searchVal;
        }
        if(onlineStatus == 0 || onlineStatus == 1)
            url_Address = url_Address+"&onlineStatus="+onlineStatus;*/ //xqr
        //alert(url_Address);  //yw 调试方法1 或layer.msg(url_Address)
        tableIns.reload({
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                buildId:tBuildID_v, //xqr 添加参数
                status: onlineStatus,
                gateWayId:searchVal
            },
            url:url_Address
        });
        return false;
    });
    //yw 监听导航事件
    $("[name=t1]").click(function (){
        var searchVal = $(".searchVal").val().trim();
        tBuildID_v =  $(this).attr("tBuildID");
        var url_Address = '/device/queryDevice';
       /* var url_Address = '/device/queryDevice?buildId='+tBuildID_v;
        var onlineStatus = $("#onlineStatus").val();
        if(searchVal!=""){
            url_Address = url_Address+"&afGateway="+searchVal;
        }
        if(onlineStatus == 0 || onlineStatus == 1)
            url_Address = url_Address+"&onlineStatus="+onlineStatus;*/ //xqr
        //alert(url_Address);
        tableIns.reload({
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                buildId: tBuildID_v //xqr 添加参数
            },
            url : url_Address //模糊查询
        });
        return false;
    });
    //yw 3操作 2)新增 (a)打开添加的弹出层
    $(".add_btn").click(function(){
        mainIndex = layer.open({
            title : ['添加网关','font-size:18px;text-align:center;color:blue;'],
            type : 1, //yw 0.默认信息框,1.page,2.iframe,3.加载层,4.tips层
            content : $("#addDiv"),//yw ,$("#addDiv"),type:1 | "gatewayAdd.html", type:2
            area:['400px','550px'],
            offset:'r',
            success : function(){
                if(schoolData == null) {
                    $.ajax({ //yw 从后台获取学校数据，填充前端的学校下拉框
                        url:'/school/getAllSchoolName',
                        dataType:'json',
                        type:'post',
                        success:function(data2){
                            schoolData = data2;
                            //console.log(schoolData);  //yw 调试方法2
                            $.each(data2,function(index,item){
                                //console.log(item); //yw 调试方法2
                                $("#schoolId").append(new Option(item.name,item.id));
                            });
                            form.render("select");
                        }
                    })
                }else{
                    $("#schoolId").empty();
                    $.each(schoolData,function(index,item){
                        $("#schoolId").append(new Option(item.name,item.id));
                    });
                    form.render("select");
                }
            }
        })
    });
    //yw 改变学校下拉框的选项，填充教学楼下拉框 lay-filter="schoolId2"
    form.on("select(schoolId)",function(){
        $.ajax({ //yw 从后台获取教学楼数据，填充前端的教学楼下拉框
            url:'/school/getAlltBuildNameID?schoolID='+$("#schoolId").val(),
            async:false,
            dataType:'json',
            type:'post',
            success:function(res){
                tBuildData = res;
                $("#tbuildName").empty();
                $.each(tBuildData,function(index,item){
                    $("#tbuildName").append(new Option(item.tbuildname,item.tbuildid));
                });
                form.render("select");
            }
        })
    });
    //yw 改变新增界面的教学楼下拉框选项，填充教室下拉框 lay-filter="classroom"
    form.on("select(tbuildName)",function(){
        $.ajax({
            //xqr 通过buildId查询教室
            url:'/classroom/queryClassRoomById?buildID='+$("#tbuildName").val()+'&page=1&limit=50',
            // url:'/classroom/queryClassroomBytBuildId?tBuildId='+$("#tbuildName").val(),
            async:false,
            dataType:'json',
            type:'post',
            success:function(res){
                classroomData = res.data;
                $("#classroom").empty();
                $.each(classroomData,function(index,item){
                    $("#classroom").append(new Option(item.classroom,item.classroomid));
                });
                form.render("select");
            }
        })
    });
    //xqr 改变新增界面的教室下拉框选项，填充网关下拉框 lay-filter="classroom"
    form.on("select(classroom)",function(){
        $.ajax({
            //xqr 通过buildId查询教室
            url:'/gateway/queryGateWayByClassroomId?classroomId='+$("#classroom").val(),
            async:false,
            dataType:'json',
            type:'post',
            success:function(res){
                var afgatewayData = res;
                $("#afgateway").empty();
                $.each(afgatewayData,function(index,item){
                    $("#afgateway").append(new Option(item.gatewaymac,item.gatewayid));
                });
                form.render("select");
            }
        })
    });
    //yw 3操作 2)新增 (b)提交监听事件--新增记录
    form.on("submit(doSubmitAdd)",function(){
        $.ajax({
            type:"post",
            url:"/device/addDevice",
            //xqr 设备信息
            data:{schoolid:$("#schoolId").val(),tbuildingid:$("#tbuildName").val(),classroomid:$("#classroom").val(),eqid:$("#eqid").val(),eqtype:$("#eqtype").val(),afgateway:$("#afgateway").val(),onlstatus:$("#onlstatus").val()},
            // data:{schoolid:$("#schoolId").val(),tbuildid:$("#tbuildName").val(),classroomid:$("#classroom").val(),classroom:$("#classroom").find("option:selected").text(),eqid:$("#eqid").val(),eqname:$("#eqname").val(),eqtypeid:$("#eqtype").val(),eqtypename:$("#eqtype").find("option:selected").text(),afgateway:$("#afgateway").val(),onlstatus:$("#onlstatus").val()},
            success:function(res){
                if(res===1){
                    tableIns.reload();
                    layer.msg('新增成功',{icon:7,time:800,shade:[0.6,'#000',true]});
                }
/*                if(res == 2) {
                    layer.msg('设备id重复，请更换！',{icon:7,time:800,shade:[0.6,'#000',true]});
                }*/
                else{
                    layer.msg('新增失败',{icon:7,time:800,shade:[0.6,'#000',true]});
                }
                tableIns.reload();
                layer.closeAll('page'); //yw 关闭新增界面
            }
        });
    });
    //yw 监听行工具条的事件
    table.on("tool(list)", function(obj){
        var   data = obj.data; //获得当前行数据
        switch(obj.event){
            case 'edit':
                openUpdateLayer(data);
                break;
            case 'del':
                deleteInfo(data);
                break;
            case 'detail':
                detailInfo(data);
                break;
            case 'datastat':
                // console.log(obj);
                datastat(data);
                break;
        };
    });
    //yw 3操作 3)更新  (a)打开修改的弹出层
    function openUpdateLayer(data){
        mainIndex = layer.open({
            title : ['修改设备','font-size:18px;text-align:center;color:blue;'],
            type : 1,
            content : $("#saveDiv"),
            area:['400px','550px'],
            offset:'r',
            success:function(layero,index){ //yw layero是弹出层对象layer object
                //console.log(data);
                if(schoolData == null) {
                    $.ajax({ //yw 从后台获取学校数据，填充前端的学校下拉框
                        url:'/school/getAllSchoolName',
                        async:false, //yw 取消异步下载模式，否则shoolId2第一次打开没有数据，第二次打开才有数据
                        dataType:'json',
                        type:'post',
                        success:function(res){
                            schoolData = res;
                            $.each(schoolData,function(index,item){
                                $("#schoolId2").append(new Option(item.name,item.id));
                            });
                        }
                    })
                }else{
                    $("#schoolId2").empty();
                    $.each(schoolData,function(index,item){
                        $("#schoolId2").append(new Option(item.name,item.id));
                    });
                }
                $("#afgateway2").val(data.afgateway);
                //var schoolId = data.tbuildid.substring(0,3);
                $("#schoolId2").val(data.schoolid);
                form.render("select");
                $("#eqid2").val(data.eqid);
                $("#eqname2").val(data.eqname);
                $("#classroomid2").val(data.classroomid);
                $("#eqtype2").val(data.eqtypeid);
                form.render("select");
                $("#onlinestatus2").val(data.onlstatus);

                if(tBuildData == null){
                    $.ajax({ //yw 从后台获取教学楼数据，填充前端的教学楼下拉框
                        url:'/school/getAlltBuildNameID?schoolID='+ data.schoolid,
                        async:false,
                        dataType:'json',
                        type:'post',
                        success:function(res2){
                            tBuildData = res2;
                            $("#tbuildName2").empty();
                            $.each(res2,function(index,item){
                                $("#tbuildName2").append(new Option(item.tbuildname,item.tbuildid));
                            });
                        }
                    })
                }else{
                    $("#tbuildName2").empty();
                    $.each(tBuildData,function(index,item){
                        $("#tbuildName2").append(new Option(item.tbuildname,item.tbuildid));
                    });
                }
                $("#tbuildName2").val(data.tbuildid);
                form.render("select");
                //
                if(classroomData == null){
                    $.ajax({ //yw 从后台获取教室数据，填充前端的教室下拉框
                        url:'/classroom/queryClassroomBytBuildId?tBuildId='+$("#tbuildName2").val(),
                        async:false,
                        dataType:'json',
                        type:'post',
                        success:function(res2){
                            classroomData = res2;
                            $("#classroom2").empty();
                            $.each(classroomData,function(index,item){
                                $("#classroom2").append(new Option(item.classroom,item.classroomid));
                            });
                            form.render("select");
                        }
                    })
                }else{
                    $("#classroom2").empty();
                    $.each(classroomData,function(index,item){
                        $("#classroom2").append(new Option(item.classroom,item.classroomid));
                    });
                }
                $("#classroom2 option:selected").text(data.classroom);
                $("#eqtype2 option:selected").text(data.eqname);
                form.render("select");

            }
        });
    }
    //yw 改变学校下拉框的选项，填充教学楼下拉框 lay-filter="schoolId2"
    form.on("select(schoolId2)",function(){
        $.ajax({ //yw 从后台获取教学楼数据，填充前端的教学楼下拉框
            url:'/school/getAlltBuildNameID?schoolID='+$("#schoolId2").val(),
            async:false,
            dataType:'json',
            type:'post',
            success:function(res){
                tBuildData = res;
                $("#tbuildName2").empty();
                $.each(tBuildData,function(index,item){
                    $("#tbuildName2").append(new Option(item.tbuildname,item.tbuildid));
                });
                form.render("select");
            }
        })
    });
    //yw 改变修改界面的教学楼下拉框选项，填充教室下拉框 lay-filter="classroom"
    form.on("select(tbuildName2)",function(){
        $.ajax({
            //xqr 通过buildId查询教室
            url:'/classroom/queryClassRoomById?buildID='+$("#tbuildName").val()+'&page=1&limit=50',
            // url:'/classroom/queryClassroomBytBuildId?tBuildId='+$("#tbuildName2").val(),
            async:false,
            dataType:'json',
            type:'post',
            success:function(res){
                classroomData = res.data;
                $("#classroom2").empty();
                $.each(classroomData,function(index,item){
                    $("#classroom2").append(new Option(item.classroom,item.classroomid));
                });
                form.render("select");
            }
        })
    })
    //yw 3操作 3)更新 (b)提交监听事件--修改记录
    form.on("submit(doSubmitSave)",function(){
        $.ajax({
            type:"post",
            url:"/device/saveDevice",
            //xqr 设备信息
            data:{schoolid:$("#schoolId2").val(),tbuildingid:$("#tbuildName2").val(),classroomid:$("#classroom2").val(),eqid:$("#eqid2").val(),eqtype:$("#eqtype2").val(),afgateway:$("#afgateway2").val(),onlstatus:$("#onlstatus2").val()},
            // data:{schoolid:$("#schoolId2").val(),tbuildid:$("#tbuildName2").val(),classroomid:$("#classroom2").val(),classroom:$("#classroom2").find("option:selected").text(),eqid:$("#eqid2").val(),eqname:$("#eqname2").val(),eqtypeid:$("#eqtype2").val(),eqtypename:$("#eqtype2 option:selected").text(),afgateway:$("#afgateway2").val(),onlstatus:$("#onlstatus2").val()},
            success:function(res){
                if(res){
                    tableIns.reload();
                    layer.msg('保存成功',{icon:7,time:800,shade:[0.6,'#000',true]});
                }else{
                    layer.msg('保存失败',{icon:7,time:800,shade:[0.6,'#000',true]});
                }
                layer.closeAll('page'); //yw 关闭新增界面 type=1
            }
        });
    });
    //yw 3操作 4)删除
    function deleteInfo(data){
        layer.confirm('你确定要删除[设备ID='+data.eqid+']这条数据吗?',{icon:3,title:'提示'},function(index){
            $.ajax({
                type:"POST",
                url:'/device/delDevice?eqId='+data.eqid,
                success:function(res){
                    if(res){
                        tableIns.reload();
                        layer.msg('删除成功',{icon:7,time:800,shade:[0.6,'#000',true]});
                    }else{
                        layer.msg('删除失败',{icon:7,time:800,shade:[0.6,'#000',true]});
                    }
                }
            });
            layer.close(index); //yw 关闭删除提示对话框
        });
    }
    //yw 3操作 5)详情
    function detailInfo(data){
        //console.log(data);
        mainIndex = layer.open({
            title : ['设备详情','font-size:18px;text-align:center;color:blue;'],
            type : 2,
            content : "deviceDetail.html?tbuildid="+data.tbuildid+"&tbuildname="+data.tbuildname+"&classroomid="+data.classroomid+"&classroom="+data.classroom,
            area:['1250px','780px'],
            //offset:'r',
            success:function(layero,index){
            }
        });
    };
    //yw 4表单验证
    form.verify({
        required: [/[\S]+/, "不能为空"],
        username:[/^[a-zA-Z0-9_-]{4,16}$/,"用户名4-16位字母数字下划线减号"],
        phone: [/(^$)|^1\d{10}$/, "请输入正确的手机号"],
        email: [/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确"],
        url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
        integer: [/^\d*$/, "只能填写整数"],
        date: [/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确"],
        identity: [/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号"],
        macAddress:[/^[A-F0-9:]{17}$/,"参考格式2C:4D:54:66:42:B8"],
        // 校验两次密码是否一致
        userPwd: [/(.+){6,12}$/, '密码必须6到12位'],
        userPwdCheck:function(value){
            if($('input[name=userPwd]').val() !== value)
                return '两次密码输入不一致！';
        },
        number: function (e) {
            if (e && isNaN(e))return "只能填写数字"
        },
        lenLimit10:function(value){
            if(value.length>10) return '长度不能超过10个字符';
        },
        lenLimit20:function(value){
            if(value.length>20) return '长度不能超过20个字符';
        },
        lenLimit50:function(value){
            if(value.length>20) return '长度不能超过50个字符';
        },
        lenLimit100:function(value){
            if(value.length>100) return '长度不能超过50个字符';
        }
    });

    // var count = 0;
    //yw 3操作 5)详情
    function datastat(data) {

        // if(count === 0) {
        //     count++;
        // }else {
        var tbuildname = '';
        var classroom = '';
            $('.datastat').on('click', function () {
                tbuildname = data.tbuildname;
                classroom = data.classroom;

                // console.log(this);
                var othis = $(this), method = othis.data('method');
                active[method] ? active[method].call(this, othis) : '';
            });
            //触发事件
            var index2 = null;
            var active = {
                setTop: function () {
                    index2 = layer.open({
                        type: 2 //此处以iframe举例
                        , title: '<span style="font-size: 18px">' + tbuildname + ' 教室' + classroom + '</span>'
                        , content: '/page/device/deviceMsg.html'
                        ,cancel: function () {
                            layer.closeAll();
                        }
                    });
                    layer.full(index2);
                }
            };
            $(window).resize(function () {
                layer.full(index2);
            });
        // }
    }
});
